×
☰ See All Chapters

JPA Many-to-One Unidirectional Association Mapping

Many-To-One mapping is an association between collection of same persistence objects and their related persistence object. Many persistence objects mapped to one related persistence object. Tables of both the persistence classes will be related in database. As an example, many students belong to one address. If one persistence object uses other and in back if other is not using the first persistence object then it becomes unidirectional.

Many-to-One unidirectional Mapping example

Now let us see how this mapping is done in persistence class by going through an example.  The following code shows how to do many to one mapping. We created two entities, Address and Student. Many students belong to one address. In the Student class we annotate the address field by @ManyToOne annotation.

Database script (MySQL)

CREATE        TABLE ADDRESS(

AID INT(5) PRIMARY KEY AUTO_INCREMENT,

CITY VARCHAR(30),

ZIPCODE VARCHAR(30)

);                

 

CREATE TABLE STUDENT(

SID INT(5) PRIMARY KEY AUTO_INCREMENT,

SNAME VARCHAR(30),

AID INT(5),

CONSTRAINT FOREIGN KEY (AID) REFERENCES ADDRESS (AID)

);

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.java4coding</groupId>

        <artifactId>M21_UnidirectionalAssociationMapping</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>M21_UnidirectionalAssociationMapping</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

 

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="StudentPU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

Address.java

package com.java4coding;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name = "ADDRESS")

public class Address {

       

        @Id

        private int aid;

       

        private String city;

 

        private String zipcode;

 

        public int getAid() {

                return aid;

        }

        public void setAid(int aid) {

                this.aid = aid;

        }

        public String getCity() {

                return city;

        }

        public void setCity(String city) {

                this.city = city;

        }

        public String getZipcode() {

                return zipcode;

        }

        public void setZipcode(String zipcode) {

                this.zipcode = zipcode;

        }

}

 

Student.java

package com.java4coding;

 

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

 

@Entity

@Table(name = "STUDENT")

public class Student {

       

        @Id

        @GeneratedValue(strategy = GenerationType.AUTO)

        private int sid;

       

        private String sname;

       

        @ManyToOne(cascade = CascadeType.ALL)

        @JoinColumn(name= "AID")

        private Address address;

 

        public int getSid() {

                return sid;

        }

        public void setSid(int sid) {

                this.sid = sid;

        }

        public String getSname() {

                return sname;

        }

        public void setSname(String sname) {

                this.sname = sname;

        }

        public Address getAddress() {

                return address;

        }

        public void setAddress(Address address) {

                this.address = address;

        }

}

 

Test.java

package com.java4coding;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

public class Test {

        public static void main(String[] args) {

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU");

                EntityManager em = emf.createEntityManager();

 

                em.getTransaction().begin();

 

                Address add1 = new Address();

                add1.setCity("BANGALORE");

                add1.setZipcode("560010");

                add1.setAid(1);

 

                Student stu1 = new Student();

                stu1.setSname("Manu");

                stu1.setAddress(add1);

 

                Student stu2 = new Student();

                stu2.setSname("Manjunath");

                stu2.setAddress(add1);

 

                Student stu3 = new Student();

                stu3.setSname("Advith");

                stu3.setAddress(add1);

 

                em.persist(stu1);

                em.persist(stu2);

                em.persist(stu3);

 

                // STUDENT CAN GET ADDRESS

                Student stu = em.find(Student.class, 1);

                System.out.println("student id is " + stu.getSid());

                System.out.println("student name is " + stu.getSname());

                System.out.println("student city is " + stu.getAddress().getCity());

                System.out.println("student zipcode is " + stu.getAddress().getZipcode());

 

                // ADDRESS CANNOT GET STUDENT

                /*

                Address add1 = em.find(Address.class, 1);

                System.out.println("address id is " + add1.getAid());

                System.out.println("address city is " + add1.getCity());

                System.out.println("address zipcode is " + add1.getZipcode());

                */

                em.getTransaction().commit();

        }

}

Project directory structure

jpa-many-to-one-unidirectional-association-mapping-0
 

Output

Hibernate:

    insert

    into

        ADDRESS

        (city, zipcode, aid)

    values

        (?, ?, ?)

Hibernate:

    insert

    into

        STUDENT

        (AID, sname)

    values

        (?, ?)

Hibernate:

    insert

    into

        STUDENT

        (AID, sname)

    values

        (?, ?)

Hibernate:

    insert

    into

        STUDENT

        (AID, sname)

    values

        (?, ?)

student id is 1

student name is Manu

student city is BANGALORE

student zipcode is 560010

 


All Chapters
Author